#
# @lc app=leetcode.cn id=42 lang=python3
#
# [42] 接雨水
#

# @lc code=start
from typing import List


class Solution:
    def trap(self, height: List[int]) -> int:
        if len(height) == 1:
            return 0

        sum = 0
        left = [0, 0]
        right = [0, 0]

        for i, j in enumerate(height):
            if i == 0:
                if j > height[i + 1]:
                    right = [i, j]
            elif i == len(height) - 1:
                if height[i - 1] < j:
                    right = [i, j]
            else:
                if height[i - 1] <= j and j >= height[i + 1]:
                    right = [i, j]

            if left[1] != 0 and right[1] != 0:
                if left[1] <= right[1]:
                    h = left[1]
                    for i in range(left[0] + 1, right[0]):
                        if height[i] < h:
                            sum += h - height[i]
                        else:
                            break
                else:
                    h = right[1]
                    for i in range(right[0] - 1, left[0], -1):
                        if height[i] < h:
                            sum += h - height[i]
                        else:
                            break
                left, right = right, [0, 0]
            elif left[1] == 0:
                left, right = right, [0, 0]
        return sum


if __name__ == '__main__':
    s = Solution()
    trap = s.trap

    print(trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) == 6)
    print(trap([0]) == 0)
    print(trap([2, 0, 2]) == 2)
    print(trap([5, 4, 1, 2]) == 1)
    print(trap([[5, 2, 1, 2, 1, 5]]) == 14)
# @lc code=end
